<template>
  <div id="lesson" :class="{ 'lesson-lessons': giveLessons }">
    <transition name="fade">
      <div class="flex-between header-nav" v-show="!giveLessons" v-if="!(isDiyLesson && !isEdit &&lessonItems.length ==0)">
        <div class="lesson-handel flex-start flex-top">
            <div v-show="!isEdit" class="handel-item flex-center pointer" @click="editResource">
                <img src="../../assets/img/home/edit.png" alt="" />
                <a class="s-14">{{ editDesc }}</a>
                <span class="separator"></span>
            </div>
            <div v-show="isEdit" class="handel-item flex-center pointer" @click="completeEdit">
                <img src="../../assets/img/home/complete.png" alt="" />
                <a class="s-14">{{ editDesc }}</a>
                <span class="separator"></span>
            </div>
            <div class="handel-item flex-center pointer" @click="upload(0)" v-show="!isEdit">
                <img src="../../assets/img/home/uploadc.png" alt="" />
                <a class="s-14">导入课件</a>
                <span class="separator"></span>
            </div>
            <div class="handel-item flex-center pointer" @click="upload(1)" v-show="!isEdit">
                <img src="../../assets/img/home/uploadv.png" alt="" />
                <a class="s-14">导入多媒体</a>
                <span class="separator"></span>
            </div>
            <div class="handel-item flex-center pointer" v-show="!isEdit" @click="uploadResource">
                <img  style="width: 20px;height: 15px;" src="../../assets/img/home/uploadCloud.png" alt="" />
                <a class="s-14">上传云端</a>
                <span class="separator"></span>
            </div>
            <div class="handel-item flex-center pointer" v-show="!isEdit" @click="syncResource">
                <img  style="width: 20px;height: 15px;" src="../../assets/img/home/sync.png" alt="" />
                <a class="s-14">云端下载</a>
                <div class="lessonRedflag" v-if="lessonRedflag && !isDiyLesson"></div>
                <span v-if="!isDiyLesson" class="separator"></span>
            </div>
            <div class="handel-item flex-center pointer" v-show="!isEdit &&  !isDiyLesson" @click="courseFeedback">
                <img style="width: 17px;height: 20px;" src="../../assets/img/home/feedback.png" alt="" />
                <a class="s-14">课程反馈</a>
            </div>
            <div class="handel-item flex-center pointer" v-show="isEdit" @click="exitEdit">
                <img src="../../assets/img/home/q-edit.png" alt="" />
                <a class="s-14">退出编辑</a>
                <!-- <span class="separator"></span> -->
            </div>
            <div class="handel-item  pointer" style="position: absolute;right:50px;display: flex;align-items: center;" v-show="isEdit" @click="initLesson" v-if="!isDiyLesson">
              <img style="margin-right: 6px;" src="../../assets/img/home/remake.png" alt="" />
              <a class="s-14">初始化</a>
            </div>
        </div>
        <div class="lesson-handel" v-show="!isEdit" style="border-radius: 0px 4px 4px 0;">
            <div class="handel-item flex-end" style="transform: translateX(-8px);">
                <div style="display: flex;align-items: center;" v-if="!isDiyLesson && !isOutLesson" @click="findMorePPt">
                    <img src="../../assets/img/home/courseRecommend.png" style="margin-right: 8px;width: 17px;height: 17px;" alt="" class="pointer" />
                    <span class="cloud-btn s-14 pointer" >参考课件</span>
                    <span class="separator"></span>
                </div>
                <div style="display: flex;align-items: center;"  @click="goResource">
                    <img style="width: 21px;height: 16px;margin-right: 8px;" src="../../assets/img/home/resource.png"  alt="" class="pointer" />
                    <span class="cloud-btn s-14 pointer">资源中心</span>
                </div>
            </div>
        </div>
      </div>
    </transition>

    <div class="lesson-res-con flex-1" ref="lessonCon"  > 
        <div class="lesson-res">
            <!-- :disabled="isEdit" -->
            <draggable v-model="lessonItems" :disabled="!isEdit" class="resItem"  force-fallback="true" group="name" animation="300"  @start="onStart" @end="onEnd" :move="moveLes"  ghost-class="ghost">
                <!-- <transition-group> -->
                <div class="l-r-items"   v-for="(v) in lessonItems" :key="v.id"  draggable="true" >
                    <span v-if="v.isDefault === '1' && (v.downloadInfo.FileType == 'courseware' || v.downloadInfo.FileType == 'selfPpt')" class="default-ppt">默认PPT</span>
                    <span v-if="v.isDefault !== '1' && v.scene" class="resLabel">{{v.scene}}</span>
                    <div class="thumbnail-container pointer" @click.prevent="showResource(v)">
                        <img v-if="v.downloadInfo.FileType === 'selfPpt'" src="../../assets/img/home/selfPptThumb.png" />
                        <img v-if="v.downloadInfo.FileType === 'selfPdf' || v.downloadInfo.FileType === 'selfWord'" src="../../assets/img/home/selfPdf-WordThumb.png" />
                        <img v-if="v.downloadInfo.FileType === 'selfImg'" src="../../assets/img/home/selfImgThumb.png" />
                        <img v-if="v.downloadInfo.FileType === 'selfVideo' || v.downloadInfo.FileType === 'selfAudio'" src="../../assets/img/home/selfVideo-AudioThumb.png" />
                        <img alt="图片加载中" v-else :src="computeThumb(v)" @error="imgLoadError" style="opacity: 0;" onload="this.style.opacity = 1" data-reload="0" />
                        <div class="resource-description" style="z-index:5" v-if="!['Quiz', 'courseware', 'selfPpt', 'selfPdf','selfWord','selfImg','selfVideo','selfAudio'].includes(v.downloadInfo.FileType)">
                            <div class="s-16">资源简介</div>
                            <div class="description-content">
                                {{ computeBref(v) }}
                            </div>
                        </div>
                        <div class="downloadFail align-center" v-if="v.downloadStatus === '1'">
                            <div class="download-again pointer" @click="resumeDownload(v)" v-if="isOnline()">
                                <img src="../../assets/img/home/reload-lesson.png" alt="" />
                                重新下载
                            </div>
                        </div>
                        <div class="downloadFail align-center" v-if="v.downloadStatus === '2'">
                            <div class="download-again pointer" @click="resumeDownload(v)" v-if="isOnline()">
                                <img src="../../assets/img/home/download_Cloud.png" alt="" />
                                未下载
                            </div>
                        </div>
                    </div>
                    <div class="lesson-message">
                        <div class="res-name" :style="v.name.length > 6 || `width:${v.name.length}em`">
                            <div class="txt s-18 ">
                                {{ v.name }}
                            </div>
                            <div class="s-18 title" :data-name="v.name">
                                {{ v.name }}
                            </div>
                        </div>
            
                        <span class="separator"></span>
                        <span class="res-type s-14">{{ v | resType }}</span>
                        <!-- <button v-if="v.downloadInfo.FileType === 'selfPpt' && !isEdit && !v.isUpload" class="lesson-item-btn s-16" @click="uploadUserPPt(v)">
                            上传云端
                        </button> -->
                        <button v-if="!['courseware', 'selfPpt'].includes(v.downloadInfo.FileType) && isEdit " class="lesson-item-btn s-16" style="color: #F56C6C;padding-right: 10px;" @click="deleteResourceHandle(v)">
                            删除
                        </button>
                    </div>
                    <div class="category" v-if="v.downloadInfo.FileType !== 'courseware'"></div>
                    <div v-if="['courseware', 'selfPpt'].includes(v.downloadInfo.FileType) && isEdit" class="dropdown-menu-container" @click.stop="collapseActive(v)">
                        <el-dropdown trigger="click" @command="command" class="lesson-dropdwon s-16">
                            <button class="lesson-edit-btn s-16">
                              <span style="display: inline-block; transform: translateX(-24px);cursor: pointer;">编辑</span>
                              <img src="../../assets/img/home/collapse-up.png" alt="" v-if="!v.collapse" />
                              <img src="../../assets/img/home/collapse.png" alt="" v-if="v.collapse" />
                            </button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item class="s-16" :command="{ type: '4', id: v.downloadInfo.TaskId, value: v }" v-if="v.downloadInfo.FileType === 'courseware'">
                                    初始化课件
                                </el-dropdown-item>
                                <el-dropdown-item class="s-16" :command="{ type: '1', value: v }">
                                    导出课件
                                </el-dropdown-item>
                                <el-dropdown-item class="s-16" v-if="v.isDefault !== '1'" :command="{ type: '5', id: v.downloadInfo.TaskId, value: v }">
                                    移除课件
                                </el-dropdown-item>
                                <el-dropdown-item
                                v-if="(v.resType == 'PPT') && v.isDefault !== '1' && isEdit"
                                class="s-16"
                                :command="{
                                  type: '2',
                                  id: v.downloadInfo.FileType === 'selfPpt' ? v.id : v.downloadInfo.TaskId,
                                }"
                            >
                                设为默认PPT
                                </el-dropdown-item>  
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                    <!-- <div v-if="isEdit" class="edit_wrapper">
                        <div class="singleEdit" v-show="['courseware'].includes(v.downloadInfo.FileType)" @click="command({ type: '4', id: v.downloadInfo.TaskId, value: v })">初始化</div>
                        <div class="singleEdit" v-show="['courseware', 'selfPpt'].includes(v.downloadInfo.FileType)" @click="command({ type: '1', value: v })">导出</div>
                        <div class="singleEdit" :class="[!['courseware', 'selfPpt'].includes(v.downloadInfo.FileType) ? 'alone' : '']" @click="command({ type: '5', id: v.downloadInfo.TaskId, value: v })">移除</div>
                    </div> -->
                    <div v-if="v.downloadStatus === '1'" class="download-fail-tips flex-center">
                        <div class="fail-logo t-color-e">!</div>
                        <div class="s-14 t-color-e">资源下载失败</div>
                    </div>
                </div>
                <div class="l-r-items pointer" @click="getResource" v-show="!isEdit && !isDiyLesson">
                    <div class="thumbnail-container pointer">
                        <img src="../../assets/img/home/jump_recommend.jpg" alt="" />
                    </div>
                    <div class="lesson-message cloud-res">
                        <div class="s-18 pointer add-res">智能推荐</div>
                    </div>
                </div>
                <!-- </transition-group> -->
            </draggable>
             
        </div>
    </div>
    
  </div>
</template>
<script>
import draggable from 'vuedraggable'
import bus from '../../assets/js/bus.js'
import { SqlLib } from '../../../../../static/lib/sqlite/SqlLib'
import { SqlLibUser } from '../../../../../static/lib/sqlite/service/SqlLibUser'
import { SqlLibBook } from '../../../../../static/lib/sqlite/service/SqlLibBook'
import usermeta from '@/content/api/usermeta'
import resource from '@/content/api/resource'
import userApi from '@/content/api/user'
import { FileDownloader } from '../../../../../static/lib/downloader/FileDownloader'
import * as qiniu from 'qiniu-js'
import { FileUtil } from '../../../../../static/utils/FileUtil'
import { Lesson } from '../../../../../static/lib/sqlite/model/Lesson'
import { DownloadCenter } from '../../../../../static/lib/downloader/DownloadCenter'
import { SetDownloaderLib } from '../../../../../static/lib/downloader/SetDownloaderLib'
import { UserResource } from '../../../../../static/lib/sqlite/model/UserResource'
import { UUIDUtil } from '../../../../../static/utils/UUIDUtil'
import { CloudResDownloader } from '../../../../../static/lib/downloader/CloudResDownloader'
import { ThumbDownloader } from '../../../../../static/lib/downloader/ThumbDownloader'
import { RecUserResource } from '../../../../../static/lib/sqlite/model/RecUserResource'
import { getAppNewVersion } from '@/content/api/appversion'
import moment from 'moment'
import { mapState } from 'vuex'
let cacheLessonItemMap = new Map() //缓存被点击的课程,message事件
const weedMetaId = ['countDown', 'extractNumber', 'tProgress', 'charts', 'mindMap', 'Picture','recognize']
const deleteSet = []
const weedMetaIdMap = {
    countDown: 'CountDown',
    extractNumber: 'ExtractNumber',
    tProgress: 'TProgress',
    charts: 'Charts',
    mindMap: 'MindMap',
    Picture: 'ImageTrans',
    recognize: 'ReadPic',
}
export default {
    name: 'Lesson',
    components:{draggable},
    data() {
    return {
        lessonItems: [],
        resourceVOList:[],
        insertItem:false,
        uploadParams: {},
        collapseItems: {},
        uploadResult: false,
        isEdit: false, //编辑资源
        syncObj: {
          downloader: null,
          loadingService: null
        },
        lessonMsg:{},
        drag:false,
        sortData:[],
        lessonRedflag:false,
        isDiyLesson:false,
        isOutLesson:false,//是否为拓展课程
    }
  },
  watch:{
    lessonItems(nval,oval){
      // console.log(nval);
      if (nval !== oval) {
        this.insertItem = true
      }
    }
  },
  mounted() {
    
    this.$nextTick(() => {
      window.addEventListener('click', e => {
        this.collapseItems.collapse = false
      })
    })
    bus.$on('pickLessonMsg',(Msg)=>{
        this.lessonMsg = Msg
        // console.log('lessonMsg',this.lessonMsg);
    })
    bus.$on('downloadAgain',()=>{
        this.restCurrentLesson()
    })
    bus.$on('isOutLesson', (val)=>{
        this.isOutLesson = val
        // console.log('val---------------------',val);
    })
    this.setLessonWidth()
    // window.addEventListener('resize', this.setLessonWidth)
    const recordMessage = new BroadcastChannel('record-time')
    recordMessage.addEventListener('message', e => {
      console.log('e.data---->', e.data)
      const { metaId, playTime, startTime } = e.data
      if (!metaId) return
      if (this.isOnline()) {
        if (weedMetaId.includes(metaId)) {
          let param = {
            toolType: weedMetaIdMap[metaId],
            lessonId: this.uploadParams.lessonId,
            useTime: playTime,
            startTime: moment(new Date(startTime)).format('YYYY-MM-DD HH:mm:ss'),
            type:this.isDiyLesson ? 1 : 0
          }
          this.recordToolTime({ useTechToolDTOList: [param] })
        } else {
          let param = cacheLessonItemMap.get(metaId)
          console.log('param------------------------',param);
          param.playTime = playTime
          this.recordResTimeIsOnLine(param)
        }
      } else {
        if (weedMetaId.includes(metaId)) {
          let recUserResource = new RecUserResource()
          recUserResource.id = UUIDUtil.uuid()
          recUserResource.lessonId = this.uploadParams.lessonId
          recUserResource.userId = this.uploadParams.userId
          recUserResource.gmtCreate = moment().format('YYYY-MM-DD HH:mm:ss')
          recUserResource.metaInfoId = metaId
          recUserResource.metaType = weedMetaIdMap[metaId]
          recUserResource.playTime = playTime
          console.log('metaId-->离线统计资源播放时长');
          this.recordResTimeIsOffLine(recUserResource)
        } else {
            let param = cacheLessonItemMap.get(metaId)
            param.playTime = playTime
            console.log('nometaId-->离线统计资源播放时长',param);
            this.recordResTimeIsOffLine(param)
        }
      }
    })
  },
  filters: {
    resType(v) {
        if (v.downloadInfo.FileType === 'selfPpt' && v.isUpload) return 'PPT'
        return v.resType.replace(/.*\s(?=|)/g, '')
    }
  },
  computed: {
    ...mapState(['giveLessons']),
    editDesc() {
      return this.isEdit ? '保存编辑' : '编辑排序'
    }
  },
  beforeDestroy() {
    window.removeEventListener('click', e => {})
  },
  methods: {
    // formatName(name){
    //     if(name.lastIndexOf('.') > 0){
    //         let newName = name.substring(0,name.lastIndexOf('.'))
    //         return newName
    //     }else{
    //         return name
    //     }
    // },
    fileCommand(command){        
        switch (command) {
            case 0:
                this.upload(0)
                break
            case 1:
                this.upload(1)
                break
            default:
                break;
        }
    },
    courseFeedback(){
        bus.$emit('showFeedback')
        setTimeout(() => {
            bus.$emit('passLessonMsg', this.lessonMsg)
        }, 0);
    },
    onStart() {
        
    },
    onEnd() {
        this.sortData = []
        this.drag = true
        this.lessonItems.forEach((item,index)=>{
            if (item.resType == 'PPT'||
                item.resType == '文档'||
                item.resType == '图片'||
                item.resType == '视频'||
                item.resType == '音频') {
                this.sortData.push({
                    res_id:item.downloadInfo.FileName,
                    sortIndex:index,
                })
            }else{
                this.sortData.push({
                    res_id:item.id,
                    sortIndex:index,
                })
            }
        })
    },
    moveLes(){
        console.log('move');
    },
    findMorePPt(){
        var weburl = ''
        const shell = require('electron').shell;
        userApi.getWebAccessToken({
        }).then(res=>{
            if (res.code === '0') {
                const {publishId,bookId,unitId,lessonId} = this.lessonMsg 
                console.log(publishId,bookId,unitId,lessonId);
                console.log(res.returnValue.accessToken);
                var baseUrl = process.env.NODE_ENV === 'production' ? 'https://'+res.returnValue.openWebDomain +'/jy/index.html#/course?webToken=' :'https://'+res.returnValue.openWebDomain+'/jy/index.html#/course?webToken='
                var LessonUrl = '&publishId='+publishId+'&bookId='+bookId+'&unitId='+unitId+'&lessonId='+lessonId
                weburl = baseUrl+res.returnValue.accessToken+LessonUrl
                shell.openExternal(weburl)
            }else{
                weburl = process.env.NODE_ENV === 'production' ? 'https://'+res.returnValue.openWebDomain+'/jy/index.html#/' : 'https://'+res.returnValue.openWebDomain+'/jy/index.html#/'
                shell.openExternal(weburl)
            }
        })
    },
    // 退出编辑
    exitEdit(msg) {
        if (msg == 'goclass') {
            this.isEdit = false
            deleteSet.length = 0
            if (this.isDiyLesson)  {
                bus.$emit('initDiyLesson', this.uploadParams.lessonId) 
            }else{
                bus.$emit('initLesson', this.uploadParams.lessonId, () => (this.isEdit = true))
            }
            return
        }
        this.$dialog({
            confirm: '保存',
            cancel: '退出',
            message: '尚未保存编辑内容，是否退出编辑模式?',
            close: false,
            type: 'warn',
            title:'温馨提示'
        }).then(()=>{
            this.completeEdit()
        }).catch(()=>{
            this.isEdit = false
            deleteSet.length = 0
            if (this.isDiyLesson)  {
                bus.$emit('initDiyLesson', this.uploadParams.lessonId) 
            }else{
                bus.$emit('initLesson', this.uploadParams.lessonId, () => (this.isEdit = true))
            }
            bus.$emit('isshowdownloadAgain' , false)
        })
        
    },
    //保存编辑
    completeEdit() {
        bus.$emit('isshowdownloadAgain' , false)
        if (this.drag) {
            console.log(this.sortData);
            var resSortInfo = JSON.stringify(this.sortData)
            resource.saveUserLesResSort({
                lessonId:this.uploadParams.lessonId,
                resSortInfo:resSortInfo,
                type:this.isDiyLesson ? 1 : 0
            }).then(res=>{
                console.log(res);
                if (res.code == '0') {
                    this.drag = false
                }
            })
        }
        try {
          if (deleteSet.length > 0) {
            deleteSet.forEach((item ,i) => {
              console.log('deleteSet',item);
              this.deleteResource(item)
            })
            this.$message.success('编辑成功')
          }
        } catch (error) {
          this.$message.error('编辑失败')
        }
        deleteSet.length = 0
        this.isEdit = false
        if (this.isDiyLesson)  {
            setTimeout(() => {
                bus.$emit('initDiyLesson', this.uploadParams.lessonId) 
            }, 200);
        }else{
            bus.$emit('initLesson', this.uploadParams.lessonId,true)
        }
    },
    deleteResourceHandle(v) {
        deleteSet.push(v)
        const index = this.lessonItems.findIndex(item => item.id === v.id)
        this.lessonItems.splice(index, 1)
    },
    setLessonWidth() {
      this.$nextTick(() => {
        const { size } = require('electron').remote.screen.getPrimaryDisplay()
        console.log(size)
        const lessonCon = this.$refs.lessonCon
        if (lessonCon) {
          const resizeObserver = new ResizeObserver(entries => {
            const { width } = entries[0].contentRect
            const surplus = width - 376 * Math.floor((width - 347) / 376) - 347
            // console.log('surplus------>', surplus)
            lessonCon.style.setProperty('--width', `${surplus}px`)
          })
          resizeObserver.observe(lessonCon)
          // const { width } = lessonCon.getBoundingClientRect()
          // console.log(window.innerWidth)
          // console.log(Math.floor((width - 347) / 376))
          // const width = window.innerWidth - 380px
          // const surplus = width - 376 * Math.floor((width - 347) / 376) - 347
          // console.log('surplus------>', surplus)
        }
      })
    },
    initLesson(){//初始化课程、删除用户、资源、课程关联关系；删除用户、课程、单个文件的关系
        const isOffline = localStorage.getItem('isOffline')
        if (isOffline !== 'false') return this.$message.error('网络异常，无法重置')
        this.$dialog({
          confirm: '确认',
          cancel: '取消',
          message: '确认初始化为系统默认资源?',
          close: false,
          type: 'warn'
        }).then(() => {
            let _this = this
            this.lessonItems.forEach(item=>{
                let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR))
                const path = require('path')
                switch (item.downloadInfo.FileType) {
                    case _this.$CONST.global.selfPpt:
                        FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'ppt', user.id, item.downloadInfo.FileName))
                        break;
                    case _this.$CONST.global.selfPdf:
                        FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'pdf', user.id, item.downloadInfo.FileName))
                        break;
                    case _this.$CONST.global.selfWord:
                        FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'word', user.id, item.downloadInfo.FileName))
                        break;
                    case _this.$CONST.global.selfImg:
                        FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'img', user.id, item.downloadInfo.FileName))
                        break;
                    case _this.$CONST.global.selfVideo:
                        FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'video', user.id, item.downloadInfo.FileName))
                        break;
                    case _this.$CONST.global.selfAudio:
                        FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'audio', user.id, item.downloadInfo.FileName))
                        break;
                    default:
                        break;
                }
                var userResource = SqlLibBook.queryOneResourceByName(SqlLib.getInstance(window.$DBDIR), this.uploadParams.userId, this.uploadParams.lessonId,item.downloadInfo.FileName)
                if (item.downloadInfo.FileType === this.$CONST.global.selfPpt   ||
                    item.downloadInfo.FileType === this.$CONST.global.selfPdf   ||
                    item.downloadInfo.FileType === this.$CONST.global.selfWord  ||
                    item.downloadInfo.FileType === this.$CONST.global.selfImg   ||
                    item.downloadInfo.FileType === this.$CONST.global.selfVideo ||
                    item.downloadInfo.FileType === this.$CONST.global.selfAudio) {
                    SqlLibBook.deleteLessonResource(SqlLib.getInstance(window.$DBDIR), {
                        lessonId: this.uploadParams.lessonId,
                        resourceId: userResource.id
                    })
                }else{
                    SqlLibBook.deleteLessonResource(SqlLib.getInstance(window.$DBDIR), {
                        lessonId: this.uploadParams.lessonId,
                        resourceId: item.id
                    })
                }
            })
            usermeta.deleteUserFile({
                lessonId: this.uploadParams.lessonId,
            }).then(res=>{
                console.log(res);
            })
            usermeta.deleteUserLessonMeta({
                lessonId:this.uploadParams.lessonId,
            }).then(res=>{
                console.log(res);
                this.setUserLessonVer()
            })
            resource.deleteUserLesResSort({
                lessonId:this.uploadParams.lessonId
            }).then(res=>{
            })
            // return
            let sqlLib = SqlLib.getInstance(window.$DBDIR)
            SqlLibBook.resetDefaultPpt(sqlLib, this.uploadParams.lessonId)
            _this.isEdit = false
            bus.$emit('isshowdownloadAgain' , false)
            this.lessonRedflag = false
            bus.$emit('resetDownload')
        })
    },
    restCurrentLesson() {//一件重置功能、不删除用户、资源、课程关联关系
        const isOffline = localStorage.getItem('isOffline')
        if (isOffline !== 'false') return this.$message.error('网络异常，无法重置')
        this.$dialog({
          confirm: '确认',
          cancel: '取消',
          message: '确认重新下载当前页面资源?',
          close: false,
          type: 'warn'
        }).then(() => {
            let sqlLib = SqlLib.getInstance(window.$DBDIR)
            SqlLibBook.resetDefaultPpt(sqlLib, this.uploadParams.lessonId)
            bus.$once('cancelEdit', () => {
                this.isEdit = false
            })
            bus.$emit('resetDownload')
            bus.$emit('isshowdownloadAgain' , false)
            resource.deleteUserLesResSort({
                lessonId:this.uploadParams.lessonId
            }).then(res=>{
            })
        })
    },
    uploadCompleted() {
      // this.$message.success('导入文件成功')
      if (this.isDiyLesson) {
        bus.$emit('initDiyLesson', this.uploadParams.lessonId) 
      }else{
        bus.$emit('initLesson', this.uploadParams.lessonId) 
      }
    },
    upload(type) {
      if (this.isEdit) {
        this.$message.warning('请先完成编辑资源！')
        return
      }
      this.$showOpenDialog(type, this.uploadParams, this.uploadCompleted)
    },
    getUserSpace(){//获取上传空间大小
        resource.getUserSpace({
            appKey:'NOVO_EDU_BEAUTY_SCIENCE_PC'
        }).then( res =>{
            if (res.code == '0') {
                localStorage.setItem('spaceSize',res.returnValue.totalSize)
                if(res.returnValue.usedSize > res.returnValue.totalSize){
                    localStorage.setItem('spaceusedSize',res.returnValue.totalSize) 
                }else{
                    localStorage.setItem('spaceusedSize',res.returnValue.usedSize) 
                }
            }
            // console.log('ssssss',res);
        })
    },
    //批量上传云端记录
    createUserBatchFiles(fileKeyList,loadingInstance,isOverSize){
        console.log('createUserBatchFiles');
        let syncFileDTOS = []  //已经上传过云端的资源
        let _this = this
        if(_this.isDiyLesson){
            resource.queryDiyLessonFile({
                lessonId:_this.uploadParams.lessonId
            }).then(res=>{
                console.log('res',res);
                if (res.returnValue.userFileVOS) {
                    res.returnValue.userFileVOS.forEach(item=>{
                        _this.lessonItems.forEach(val=>{
                            if (item.fileMd5 == val.fileMd5) {
                                syncFileDTOS.push(item.fileId)//已上传的资源
                            }
                        })
                    })
                }
            })
        }else{
            usermeta.getAllUserLessonFile({//统计已经上传过云端的资源
                withFileUrl: '1',
                lessonId: _this.uploadParams.lessonId
            }).then(res=>{
                if (res.code == '0'){
                    res.returnValue.forEach(item=>{
                        _this.lessonItems.forEach(val=>{
                            if (item.fileMd5 == val.fileMd5) {
                                syncFileDTOS.push(item.fileId)//已上传的资源
                            }
                        })
                    })
                }
            })
        }
        // return
        setTimeout(() => {
            resource.createUserBatchFiles({
                lessonId:_this.uploadParams.lessonId,
                selfFileDTOS:fileKeyList,
                syncFileDTOS:syncFileDTOS,
                type: !this.isDiyLesson ? 0 : 1,
            }).then(res=>{
                console.log('res',res);
                if (res.code == '0') {
                    loadingInstance.close()
                    if (_this.isDiyLesson) {
                        _this.queryDiyResSort()
                    }
                    this.$message({message:'上传成功',type:'success',duration:3000})
                    _this.getUserSpace()
                    if (res.returnValue) {
                        res.returnValue.forEach(item=>{
                            console.log(item.displayName);
                            var displayName = item.displayName
                            let tampName = _this.uploadParams.lessonId + '-' + displayName
                            var userResource = SqlLibBook.queryOneResourceByName(SqlLib.getInstance(window.$DBDIR), _this.uploadParams.userId, _this.uploadParams.lessonId,tampName)
                            if (!userResource) {
                                if (displayName.indexOf('ppt') > -1) {//针对系统PPT
                                    var resourseId = ''
                                    _this.lessonItems.forEach(item=>{
                                        if (displayName.indexOf(item.name) > -1) {
                                            resourseId = item.id
                                        }
                                    })
                                    var userResource = SqlLibBook.queryOneResource(SqlLib.getInstance(window.$DBDIR), _this.uploadParams.userId, _this.uploadParams.lessonId,resourseId)
                                    console.log('ppt userResource',userResource);
                                }
                            }
                            if (!userResource) {
                                return
                            }
                            if (userResource.reverse2) {
                                resource.deleteUserUploadFile({
                                    fileId:userResource.reverse2
                                }).then(res=>{
                                    console.log('deleteUserUploadFile' ,res);
                                })
                            }
                            //资源已经上传云端了
                            userResource.reverse1 = item.id  //上传后文件课程关系id
                            userResource.reverse2 = item.fileId //个人资源文件id
                            userResource.reverse3 = '0' // 资源已上传云端
                            // userResource.resourceId = item.fileId
                            SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(userResource)
                            console.log('上传后',userResource);
                        })
                        if(!_this.isDiyLesson){
                            _this.setUserLessonVer()
                            bus.$emit('initLesson', _this.uploadParams.lessonId)
                        }else{
                            bus.$emit('initDiyLesson', _this.uploadParams.lessonId)
                        }
                    }
                }else{
                    loadingInstance.close()
                }
                if (isOverSize) {//有一部分文件大小超出限制
                    this.$dialog({
                        confirm: '确认',
                        cancel: '取消',
                        message: '大小超出100M的文件将自动过滤无法上传',
                        close: false,
                        type: 'warn',
                        title:'温馨提示'
                    })
                }
            })         
        }, 200);
    },
    //批量上传云端文件
    uploadResource(){
        const isOffline = localStorage.getItem('isOffline')
        if (isOffline !== 'false') {//先判断网络
            return this.$message.error('网络异常，无法上传')
        }
        if (Number(localStorage.getItem('spaceusedSize')) >= Number(localStorage.getItem('spaceSize'))) {//再判断空间大小
            this.$message.warning('上传空间不足，请您清理个人空间文件后重试')
            return
        }
        let _this = this
        var fileKeyList = []
        var isloopOver = false  //循环上传结束标识
        let isOverSize = false //是否有超出大小限制的文件
        let keyList =  []
        let count = 0
        const fs = require('fs')
        const path = require('path')
        const getEtag = require("../../utils/qetag");
        this.lessonItems.forEach(item=>{ //判断是否有未上传过的文件
            if (item.downloadInfo.FileType == "selfImg"   || 
                item.downloadInfo.FileType == "selfPpt"   ||
                item.downloadInfo.FileType == "selfPdf"   ||
                item.downloadInfo.FileType == "selfWord"  ||
                item.downloadInfo.FileType == "selfAudio" ||
                item.downloadInfo.FileType == "selfVideo" ){
                let tempName = item.downloadInfo.FileName
                let userResource = SqlLibBook.queryOneResourceByName(SqlLib.getInstance(window.$DBDIR), _this.uploadParams.userId, _this.uploadParams.lessonId,tempName)
                console.log('上传前',userResource);
                if (userResource) {
                    let bsr = JSON.parse(userResource.resourceDescription)
                    if (bsr.fileSize > 1024*1024*100) {
                        isOverSize = true
                    }
                    if (bsr.fileSize > 1024*1024*100) {
                        console.log('文件超出100M了');
                        return
                    }
                    if (userResource.reverse3 !== '0' && bsr.fileSize <= 1024*1024*100) {//已经上传的或者超出大小限制不再上传，如果是上传过后的ppt根据fileMd5判断是否有修改
                        keyList.push(item)
                    }
                    if(item.downloadInfo.FileType ==  "selfPpt" ){
                        const filePath = path.resolve(window.$DATADIR, 'resc', 'user', 'ppt', _this.uploadParams.userId, item.downloadInfo.FileName)
                        const bur = fs.readFileSync(filePath)
                        getEtag(bur).then(val => {
                            if (bsr.fileMd5  && bsr.fileMd5 !== val) {
                                console.log('修改了自上传PPT，重新上传');
                                keyList.push(item)
                                bsr.fileMd5 = val
                                userResource.resourceDescription = JSON.stringify(bsr)
                                SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(userResource)
                            }else if(!bsr.fileMd5 ){
                                console.log('可能是换电脑后拉取再修改');
                                keyList.push(item)
                                bsr.fileMd5 = val
                                userResource.resourceDescription = JSON.stringify(bsr)
                                SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(userResource)
                            }
                            console.log('md5',val);
                        })
                    }
                }
            }
            if(item.downloadInfo.FileType  == 'courseware') {
                let userResource = SqlLibBook.queryOneResource(SqlLib.getInstance(window.$DBDIR), _this.uploadParams.userId, _this.uploadParams.lessonId,item.id)
                console.log('courseware',userResource);
                let bsr = JSON.parse(userResource.resourceDescription)
                var filePath = path.resolve(window.$DATADIR, 'resc', 'courseware',  item.downloadInfo.TaskId + '.pptx')
                    if(!fs.existsSync(filePath)){
                        filePath = path.resolve(window.$DATADIR, 'resc', 'courseware', item.downloadInfo.TaskId  + '.ppt')
                    }
                const bur = fs.readFileSync(filePath)
                getEtag(bur).then(val => {
                    if (bsr.fileMd5 !== val) {
                        console.log('修改了系统ppt');
                        bsr.fileMd5 = val
                        userResource.resourceDescription = JSON.stringify(bsr)
                        keyList.push(item)
                        SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(userResource)
                    }
                })
            }
        })
        setTimeout(() => {
            console.log('需要上传的文件资源',keyList);
            if (keyList.length == 0) {
                this.$message.warning('暂无可上传的资源')
                if (isOverSize) {//刚好上传的文件都是超出大小限制
                    this.$dialog({
                        confirm: '确认',
                        cancel: '取消',
                        message: '大小超出100M的文件将自动过滤无法上传',
                        close: false,
                        type: 'warn',
                        title:'温馨提示'
                    }).then(()=>{
                    })
                }
                return
            }
            let loadingInstance = _this.$downloadmask('#lesson', {
                title: '正在上传'
            })
            keyList.forEach((item,index)=>{   
                if (
                    item.downloadInfo.FileType == "selfImg"   || 
                    item.downloadInfo.FileType == "selfPpt"   ||
                    item.downloadInfo.FileType == "selfPdf"   ||
                    item.downloadInfo.FileType == "selfWord"  ||
                    item.downloadInfo.FileType == "selfAudio" ||
                    item.downloadInfo.FileType == "selfVideo" ||
                    item.downloadInfo.FileType == "courseware" ) {
                    if (item.downloadInfo.FileType == "courseware") {
                        item.downloadInfo.FileName = item.downloadInfo.TaskId + '-' + item.name+'.pptx'
                    }
                    let tempNames = item.downloadInfo.FileName.split('-')
                    tempNames.shift()  // 去除第一个元素lessonID
                    if (tempNames.length >1) {
                        let tName = ''
                        tempNames.forEach((item,index)=>{
                            tName = tName  + item
                            if (index !== tempNames.length-1) {
                                tName = tName+'-'
                            }
                        })
                        // console.log(tName);
                        tempNames[0] =  tName
                    }
                    count++
                    let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR))
                    let config = {
                        useCdnDomain: true,
                        region: qiniu.region.z0
                    }
                    let putExtra = {
                        fname: item.downloadInfo.FileName,
                        params: {},
                        mimeType: null
                    }
                    resource.getQiniuUploadToken({
                        isOverride: '0',
                        uploadType:'12',
                        domainType: '1',
                        isPrivate:  '1',
                        fileKey:tempNames[0]//此处fileKey 只传入文件的原名称带后缀名
                    }).then(response=>{
                        if (response.code == '0'){
                            let returnValue = response.returnValue
                            let readPath = ''
                            var uploadFileType = ''
                            switch (item.downloadInfo.FileType) {
                                case 'courseware':
                                    uploadFileType = '1'
                                    break;
                                case 'selfPpt':
                                    readPath = 'ppt'
                                    uploadFileType = '1'
                                    break;
                                case 'selfPdf':
                                    readPath = 'pdf'
                                    uploadFileType = '2'
                                    break;
                                case 'selfWord':
                                    readPath = 'word'
                                    uploadFileType = '3'
                                    break;
                                case 'selfImg':
                                    readPath = 'img'
                                    uploadFileType = '4'
                                    break;
                                case 'selfVideo':
                                    readPath = 'video'
                                    uploadFileType = '5'
                                    break;
                                case 'selfAudio':
                                    readPath = 'audio'
                                    uploadFileType = '6'
                                    break;
                                default:
                                    break;
                            }
                            if(item.downloadInfo.FileType  == 'courseware'){
                                var data = fs.readFileSync(path.resolve(window.$DATADIR, 'resc', 'courseware', item.downloadInfo.TaskId + '.pptx'))
                            }else{
                                var data = fs.readFileSync(path.resolve(window.$DATADIR, 'resc', 'user', readPath, user.id, item.downloadInfo.FileName))
                            }
                            let file = new File([data], item.downloadInfo.FileName, {
                                type: 'application/vnd.ms-powerpoint'
                            })
                            let observable = qiniu.upload(file, returnValue.uploadFileKey, returnValue.uploadToken, putExtra, config)
                            const observer = {
                                next(res) {
                                    let val = Number(res.total.percent.toFixed(0))
                                    let maskProgress = new CustomEvent('maskProgress', {
                                        detail: {
                                            progress: val
                                        }
                                    })
                                    window.dispatchEvent(maskProgress)
                                },
                                error(err) {
                                    loadingInstance.close()
                                    console.log(err)
                                    _this.$message.warning('上传失败！')
                                },
                                complete(res) {
                                    fileKeyList.push({
                                        fileKey:res.key,
                                        displayName:tempNames[0],
                                        fileMd5:res.hash,
                                        fileSize:res.fsize,
                                        fileType:uploadFileType,
                                    })
                                    if (count == fileKeyList.length) {
                                        console.log('循环结束了  fileKeyList',fileKeyList);
                                        isloopOver = true
                                    }
                                    //注册下载进度监听事件
                                    let maskProgress = new CustomEvent('maskProgress', {
                                        detail: {
                                            progress: 100
                                        }
                                    })
                                    window.dispatchEvent(maskProgress)
                                    // loadingInstance.close()
                                }
                            }
                            observable.subscribe(observer) // 上传开始
                        }
                    })
                }
            })
            // return
            const Interval = setInterval(function () {
                if (isloopOver) {
                    clearInterval(Interval)
                    _this.createUserBatchFiles(fileKeyList,loadingInstance,isOverSize)
                }
            },1000)
        }, 200);
    },
    uploadUserPPt(ppt) {
      const isOffline = localStorage.getItem('isOffline')
      if (isOffline !== 'false') {
        return this.$message.error('网络异常，无法上传')
      }
      let _this = this
      let sqlLib = SqlLib.getInstance(window.$DBDIR)
      const fs = require('fs')
      const path = require('path')
      let user = SqlLibUser.queryCurrentUser(sqlLib)
      // 七牛云配置
      let config = {
        useCdnDomain: true,
        region: qiniu.region.z0
      }
      let putExtra = {
        fname: ppt.downloadInfo.FileName,
        params: {},
        mimeType: null
      }
      resource
        .getQiniuUploadToken({
          isOverride: '1',
          fileKey: user.id + '-' + ppt.downloadInfo.FileName,
          domainType: '1',
          isPrivate: '1'
        })
        .then(response => {
          if (response.code == '0') {
            let returnValue = response.returnValue
            let data = fs.readFileSync(path.resolve(window.$DATADIR, 'resc', 'user', 'ppt', user.id, ppt.downloadInfo.FileName))
            let file = new File([data], ppt.downloadInfo.FileName, {
              type: 'application/vnd.ms-powerpoint'
            })
            let observable = qiniu.upload(file, returnValue.uploadFileKey, returnValue.uploadToken, putExtra, config)
            let loadingInstance = this.$downloadmask('#lesson', {
              title: '正在上传'
            })
            const observer = {
              next(res) {
                let val = Number(res.total.percent.toFixed(0))
                let maskProgress = new CustomEvent('maskProgress', {
                  detail: {
                    progress: val
                  }
                })
                window.dispatchEvent(maskProgress)
              },
              error(err) {
                loadingInstance.close()
                console.log(err)
                _this.$message.warning('上传失败！')
              },
              complete(res) {
                //注册下载进度监听事件
                let maskProgress = new CustomEvent('maskProgress', {
                  detail: {
                    progress: 100
                  }
                })
                window.dispatchEvent(maskProgress)
                loadingInstance.close()
                usermeta
                  .createUserFile({
                    displayName: ppt.downloadInfo.FileName,
                    fileKey: res.key,
                    fileMd5: res.hash,
                    fileSize: res.fsize,
                    lessonId: _this.uploadParams.lessonId
                  })
                  .then(response => {
                    if (response.code == '0') {
                      _this.$message.success('上传成功！')
                      if (this.isDiyLesson)  {
                        bus.$emit('initDiyLesson', this.uploadParams.lessonId) 
                      }else{
                        bus.$emit('initLesson', this.uploadParams.lessonId) 
                      }
                    } else {
                      _this.$message.warning('上传失败！')
                    }
                  })
                  .catch(error => {
                    _this.$message.warning('上传失败！')
                  })
              }
            }
            observable.subscribe(observer) // 上传开始
          }
        })
    },
    collapseActive(v) {
      v.collapse = !v.collapse
      this.collapseItems = v
    },
    command(val) {
      let _this = this
      let sqlLib = SqlLib.getInstance(window.$DBDIR)
      const fs = require('fs')
      const path = require('path')
      if (val.type === '1') {
        const message = val.value
        const info = message.downloadInfo
        let rootPath = window.$DATADIR
        let path = ''
        let name = ''
        if (info.FileType === 'selfPpt') {
          path = rootPath + 'resc/user/ppt/' + this.uploadParams.userId + '/' + info.FileName
          name = info.FileName.match(/(?<=.*-).*(?=.ppt)/)[0]
        } else {
          path = rootPath + 'resc/courseware/' + info.TaskId + '.pptx'
          name = message.name
        }

        this.$showSaveLocalDialog({ path, name })
      } else if (val.type === '2') {
        let params = {
          lessonId: this.uploadParams.lessonId,
          resourceId: val.id
        }
        console.log('params------------',params);
        SqlLibBook.setDefaultPpt(sqlLib, params)
        this.lessonItems.forEach(item=>{
            if (item.isDefault == '1') {
                item.isDefault = '0'
            }
            if (item.id == val.id) {
                item.isDefault = '1'
            }
        })
        val.isDefault = '1' 
      } else if (val.type === '3') {
        this.uploadUserPPt(val.value)
      } else if (val.type === '4') {
        let url = val.value.downloadInfo.Url
        let pptPath = path.resolve(window.$DATADIR, 'resc', 'courseware', val.id + '.pptx')
        let error = null
        try {
          const renameSync = fs.renameSync(pptPath, pptPath)
        } catch (e) {
          error = e.message
        }
        if (error) {
          this.$message.error('请先关闭PPT再进行操作')
          error = null
          return
        }
        let loadingInstance = this.$downloadmask('#lesson', {
          title: '正在下载中',
          antiClockwise: true
        })
        let successCallback = () => {
          //注册下载进度监听事件
          let maskProgress = new CustomEvent('maskProgress', {
            detail: {
              progress: 100
            }
          })
          window.dispatchEvent(maskProgress)
          loadingInstance.close()
          _this.$message.success('下载成功！')
        }
        let errorCallback = () => {
          loadingInstance.close()
          _this.$message.error('下载失败！')
        }
        FileDownloader.getTotalSize(url, function(totalSize) {
          let download = new FileDownloader(url, pptPath)
          download.downloadFile(
            null,
            function(receivedBytes, speed) {
              let maskProgress = new CustomEvent('maskProgress', {
                detail: {
                  progress: parseInt((receivedBytes / totalSize).toFixed())
                }
              })
              window.dispatchEvent(maskProgress)
            },
            successCallback,
            errorCallback
          )
        })
      } else if (val.type === '5') {
        this.deleteResourceHandle(val.value)
      }
    },
    //排序方法
    compare(property){
        return function(a,b){
            var value1 = a[property];
            var value2 = b[property];
            return value1 - value2;
        }
    },
    //更新当前课程的版本号
    setUserLessonVer(){
        let _this = this
        resource.getUserLessonVer({
            lessonId:_this.uploadParams.lessonId
        }).then(res=>{
            let tempL = new Lesson()
                tempL.id = _this.uploadParams.lessonId
            let currentLesson = SqlLib.getInstance(window.$DBDIR).selectObjectById(tempL)
            if (res.returnValue) {
                if (res.returnValue.version) {
                    currentLesson.reverse1 = res.returnValue.version
                }
            }
            console.log('updata LessonVer 更新课程版本' , currentLesson);
            SqlLib.getInstance(window.$DBDIR).updateObjectById(currentLesson)
        }) 
    },
    //获取当前课程的版本号判断红点提示
    getUserLessonVer(){
        let _this = this
        resource.getUserLessonVer({
            lessonId:_this.lessonMsg.lessonId
        }).then(res=>{
            console.log('获取课程版本---------------------', res);
            let tempL = new Lesson()
                tempL.id = _this.lessonMsg.lessonId
            let currentLesson = SqlLib.getInstance(window.$DBDIR).selectObjectById(tempL)
            if (currentLesson.reverse1 == '') {//
                _this.lessonRedflag = false
            }
            if (res.returnValue) {
                if (res.returnValue.version) {
                    if ( Number(currentLesson.reverse1) < res.returnValue.version) {
                        _this.lessonRedflag = true
                    }else if( Number(currentLesson.reverse1)  == res.returnValue.version){
                        _this.lessonRedflag = false
                    }
                }
            }
            console.log('result',currentLesson);
        })
    },
    //自定义课程资源排序
    queryDiyResSort(){
        resource.queryDiyLessonFile({
            lessonId:this.uploadParams.lessonId
        }).then(res=>{
            if (!res.returnValue.sortInfo) {
                return
            }else{
                const sortInfo = JSON.parse(res.returnValue.sortInfo)
                console.log('sortInfo',sortInfo);
                sortInfo.forEach(item=>{
                    this.lessonItems.forEach(val=>{
                        if (val.resType == 'PPT' ||
                            val.resType == '文档'||
                            val.resType == '图片'||
                            val.resType == '视频'||
                            val.resType == '音频') {//用户上传的PPT
                            if (item.res_id == val.downloadInfo.FileName) {
                                val.userSort = item.sortIndex
                            }
                        }else{
                            if (item.res_id == val.id) {
                                val.userSort = item.sortIndex
                            }
                        } 
                    })
                    if(item.sortIndex){
                        let userResource = SqlLibBook.queryOneResource(SqlLib.getInstance(window.$DBDIR), this.uploadParams.userId, this.uploadParams.lessonId,item.res_id)
                        if (!userResource) {
                            return
                        }
                        // console.log(item.res_id,userResource);
                        userResource.sortIndex = item.sortIndex +1
                        SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(userResource)
                    }
                })
                this.lessonItems = this.lessonItems.sort(this.compare('userSort'))
            }
        })
    },
    //课程资源排序
    queryUserLesResSort(){
        resource.queryUserLesResSort({//
            lessonId:this.uploadParams.lessonId
        }).then(res=>{
            console.log(res);
            if (!res.returnValue) {
                return
            }
            if (res.returnValue.sortInfo) {
                const sortInfo = JSON.parse(res.returnValue.sortInfo)
                sortInfo.forEach((item)=>{
                    this.lessonItems.forEach((val,index)=>{
                        if (val.resType == 'PPT' ||
                            val.resType == '文档'||
                            val.resType == '图片'||
                            val.resType == '视频'||
                            val.resType == '音频') {//用户上传的PPT
                            if (item.res_id == val.downloadInfo.FileName) {
                                val.userSort = item.sortIndex
                            }
                        }else{
                            if (item.res_id == val.id) {
                                val.userSort = item.sortIndex
                            }
                        }
                        
                    })
                    if(item.sortIndex){
                        let userResource = SqlLibBook.queryOneResource(SqlLib.getInstance(window.$DBDIR), this.uploadParams.userId, this.uploadParams.lessonId,item.res_id)
                        if (!userResource) {
                            return
                        }
                        // console.log(item.res_id,userResource);
                        userResource.sortIndex = item.sortIndex +1
                        SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(userResource)
                    }
                })
                this.lessonItems = this.lessonItems.sort(this.compare('userSort'))
            }else{
                resource.getResAndCouesewareByLessonId({lessonId: this.uploadParams.lessonId}).then(res=>{//后台默认排序
                    if (res.code === '0') {
                        this.resourceVOList = res.returnValue.resourceVOList
                        if (res.returnValue.tResPaperFileVOList) {
                           let tResPaperFileVOList = res.returnValue.tResPaperFileVOList
                           tResPaperFileVOList.forEach(item=>{
                                if (item.index) {
                                    this.resourceVOList.push(item)
                                }
                           })
                        }
                        if (res.returnValue.resCoursewaresVOList) {
                            let resCoursewaresVOList = res.returnValue.resCoursewaresVOList
                            resCoursewaresVOList.forEach(item=>{
                                if (item.index) {
                                    this.resourceVOList.push(item)
                                }
                            })
                        }
                        // console.log(this.resourceVOList);
                        this.resourceVOList.forEach(val=>{
                            if (item.name === val.name || item.name === val.title) {
                                // console.log('哈撒给');
                                item.index = val.index
                            }
                        })
                    }
                    this.lessonItems = this.lessonItems.sort(this.compare('index'))
                })
            }
        })
    },
    initLessonItem(items, uploadParams,isCompleteEdit) {
        // console.log(uploadParams);
        let _this = this
        items.forEach(v => {
            if (['courseware', 'selfPpt'].includes(v.downloadInfo.FileType)) {
                this.$set(v, 'collapse', false)
            }
        })
        this.lessonItems = items
        this.uploadParams = {}
        this.uploadParams = uploadParams
        if (this.uploadParams.bookId == this.uploadParams.userId) {
            this.queryDiyResSort()
            this.isDiyLesson = true
        }else{
            if (isCompleteEdit == true) {
                console.log('编辑完之后更新版本号');
                this.setUserLessonVer()
            }else{
                this.getUserLessonVer()
            }
            this.queryUserLesResSort()
            this.isDiyLesson = false
        }    
        const fs = require('fs')
        const path = require('path')
        const getEtag = require("../../utils/qetag");
        this.lessonItems.forEach(item=>{
            if (item.downloadInfo.Bsr) {
                var bsr = JSON.parse(item.downloadInfo.Bsr)
                // console.log(item);
                switch (bsr.scenarios) {
                    case '0':
                        item.scene = '课程引入'
                        break;
                    case '1':
                        item.scene = '实践活动'
                        break;
                    case '2':
                        item.scene = '拓展资源'
                        break;
                    case '3':
                        item.scene = '课后活动'
                        break;
                    case '4':
                        item.scene = '课程小结'
                        break;
                    case '5':
                        item.scene = '随堂测试'
                        break;
                    default:
                        break;
                }
            }
            if (item.downloadInfo.FileType === _this.$CONST.global.selfPpt   ||
                item.downloadInfo.FileType === _this.$CONST.global.selfPdf   ||
                item.downloadInfo.FileType === _this.$CONST.global.selfWord  ||
                item.downloadInfo.FileType === _this.$CONST.global.selfImg   ||
                item.downloadInfo.FileType === _this.$CONST.global.selfVideo ||
                item.downloadInfo.FileType === _this.$CONST.global.selfAudio) {
                var userResource = SqlLibBook.queryOneResourceByName(SqlLib.getInstance(window.$DBDIR), _this.uploadParams.userId, _this.uploadParams.lessonId,item.downloadInfo.FileName)
                if (userResource) {
                    if(userResource.reverse3 == '0'){
                        item.scene = '云端资源'
                    }else{
                        item.scene = '本地资源'
                    }
                }
            }      
            if (item.downloadInfo.FileType == 'courseware' && item.downloadStatus == '0') {
                item.scene = '云端资源'
                let userResource = SqlLibBook.queryOneResource(SqlLib.getInstance(window.$DBDIR), _this.uploadParams.userId, _this.uploadParams.lessonId,item.id)
                let bsr = JSON.parse(userResource.resourceDescription)
                var filePath = path.resolve(window.$DATADIR, 'resc', 'courseware',  item.downloadInfo.TaskId + '.pptx')
                    if(!fs.existsSync(filePath)){
                        filePath = path.resolve(window.$DATADIR, 'resc', 'courseware', item.downloadInfo.TaskId  + '.ppt')
                    }
                const bur = fs.readFileSync(filePath)
                getEtag(bur).then(val => {
                    if (!bsr.fileMd5) {
                        bsr.fileMd5 = val
                        console.log('md5',val);
                        userResource.resourceDescription = JSON.stringify(bsr)
                        SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(userResource)
                    }else{
                        console.log('当前系统ppt的fileMd5值',bsr.fileMd5);
                    }
                })
            }
        })
        console.log('lessonItems--------' , this.lessonItems);
        console.log(this.uploadParams);
        localStorage.setItem('recognize_lessonId',this.uploadParams.lessonId)
        this.isEdit = false
    },
    // 进入资源中心
    goResource(){
      localStorage.removeItem('jump')
      if (localStorage.isOffline === 'true') {
        //离线状态
        this.$message.warning('您当前处于离线状态，不能进入资源中心！')
        return
      }
      if (this.isEdit) {
        this.$message.warning('请先完成编辑资源！')
        return
      }
      this.$router.push({
        name: 'cloud',
        params: { lessonId: this.uploadParams.lessonId},
      })
    },
    // 进入资源中心智能推荐
    getResource() {
        if (localStorage.isOffline === 'true') {
            //离线状态
            this.$message.warning('您当前处于离线状态，不能进入资源中心！')
            return
        }
        if (this.isEdit) {
            this.$message.warning('请先完成编辑资源！')
            return
        }
        localStorage.setItem('jump',0)
        this.$router.push({
            name: 'cloud',
            params: { lessonId: this.uploadParams.lessonId},
        })
    },
    //编辑资源开关
    editResource() {
        bus.$emit('isshowdownloadAgain' , true)
        this.isEdit = !this.isEdit
    },
    //删除资源
    deleteResource(item) {
        if (item) {
        let _this = this
        if (item.downloadInfo.Bsr) {
        let bsr = JSON.parse(item.downloadInfo.Bsr)
        usermeta.deleteUserLessonMeta({
                lessonId:this.uploadParams.lessonId,
                metaId:bsr.meta_info.id,
                type:this.isDiyLesson ? 1 : 0
            }).then(res=>{
                console.log(res);
            })
        }
        console.log(item.downloadInfo.FileType,this.$CONST.global.selfImg);
        if (item.downloadInfo.FileType === this.$CONST.global.selfPpt   ||
            item.downloadInfo.FileType === this.$CONST.global.selfPdf   ||
            item.downloadInfo.FileType === this.$CONST.global.selfWord  ||
            item.downloadInfo.FileType === this.$CONST.global.selfImg   ||
            item.downloadInfo.FileType === this.$CONST.global.selfVideo ||
            item.downloadInfo.FileType === this.$CONST.global.selfAudio) {
            let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR))
            const path = require('path')
            const fs = require('fs')
            switch (item.downloadInfo.FileType) {
                   //课件
                case _this.$CONST.global.selfPpt:
                    FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'ppt', user.id, item.downloadInfo.FileName))
                    break;
                    //视频
                case _this.$CONST.global.selfVideo:
                    
                    let videoPath = path.resolve(window.$DATADIR, 'resc', 'selfVideo',item.downloadInfo.FileName)
                    if (fs.existsSync(videoPath)) {
                        FileUtil.deleteFile(videoPath)
                    }else{
                        FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'video', user.id, item.downloadInfo.FileName))
                    }
                    break;
                    //图片
                case _this.$CONST.global.selfImg:
                    let imgPath = path.resolve(window.$DATADIR, 'resc', 'selfImg',item.downloadInfo.FileName)
                    console.log(imgPath);
                    if (fs.existsSync(imgPath)) {
                        FileUtil.deleteFile(imgPath)
                    }else{
                        FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'img', user.id, item.downloadInfo.FileName))
                    }
                    break;
                    //pdf文件
                case _this.$CONST.global.selfPdf:
                    let pdfPath = path.resolve(window.$DATADIR, 'resc', 'selfPdf',item.downloadInfo.FileName)
                    if (fs.existsSync(pdfPath)) {
                        FileUtil.deleteFile(pdfPath)
                    }else{
                        FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'pdf', user.id, item.downloadInfo.FileName))
                    }
                    break;
                    //word文件
                case _this.$CONST.global.selfWord:
                    let wordPath = path.resolve(window.$DATADIR, 'resc', 'selfWord',item.downloadInfo.FileName)
                    if (fs.existsSync(wordPath)) {
                        FileUtil.deleteFile(wordPath)
                    }else{
                        FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'word', user.id, item.downloadInfo.FileName))
                    }
                    break;
                    //音频
                case _this.$CONST.global.selfAudio:
                    let audioPath = path.resolve(window.$DATADIR, 'resc', 'selfAudio',item.downloadInfo.FileName)
                    if (fs.existsSync(audioPath)) {
                        FileUtil.deleteFile(audioPath)
                    }else{
                        FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'audio', user.id, item.downloadInfo.FileName))
                    }
                    break;
                default:
                    break;
            }
            var userResource = SqlLibBook.queryOneResourceByName(SqlLib.getInstance(window.$DBDIR), _this.uploadParams.userId, _this.uploadParams.lessonId,item.downloadInfo.FileName)
            console.log('delete userResource' ,userResource);
            usermeta.deleteUserFile({
                lessonId: _this.uploadParams.lessonId,
                fileId:userResource.reverse1,
                type:this.isDiyLesson ? 1 : 0
            })
            .then(res=>{
              console.log(res);
            })
            .catch(error => {})
        }
        console.log(item.id);
        if (item.downloadInfo.FileType === this.$CONST.global.selfPpt   ||
            item.downloadInfo.FileType === this.$CONST.global.selfPdf   ||
            item.downloadInfo.FileType === this.$CONST.global.selfWord  ||
            item.downloadInfo.FileType === this.$CONST.global.selfImg   ||
            item.downloadInfo.FileType === this.$CONST.global.selfVideo ||
            item.downloadInfo.FileType === this.$CONST.global.selfAudio) {
            SqlLibBook.deleteLessonResource(SqlLib.getInstance(window.$DBDIR), {
                lessonId: _this.uploadParams.lessonId,
                resourceId: userResource.resourceId
            })
        }else{
            SqlLibBook.deleteLessonResource(SqlLib.getInstance(window.$DBDIR), {
                lessonId: _this.uploadParams.lessonId,
                resourceId: item.id
            })
        }
      }
    },
    //同步自定义课程资源
    syncDiyResource(){
        console.log('下载自定义课程资源');
        let _this = this
        let lessonId = this.uploadParams.lessonId
        let sqlLib = SqlLib.getInstance(window.$DBDIR)
        let user = SqlLibUser.queryCurrentUser(sqlLib)
        let tableNames = SqlLibBook.queryChaAndBookNameByLessonId(sqlLib, lessonId)
        console.log('tableNames',tableNames);
        let downloadParam = {
            SetDownloadId: lessonId,
            DownloaderInfo: {
              lessonName: this.uploadParams.lessonName,
              bookName: tableNames.bookName,
              publisherName: tableNames.publisherName
            },
            DownloadParams: [],
            ActionStatus: '2' //动作的状态：0 - 下载；1 - 更新；2 - 同步
        }
        resource.queryDiyLessonFile({
            lessonId:lessonId
        }).then(res=>{
            if (res.code == '0') {
                //自上传资源
                res.returnValue.userFileVOS.forEach(item=>{
                    var downloaded = false
                    _this.lessonItems.forEach(val=>{//判断是否已下载
                        if (item.displayName.indexOf(val.name) !== -1) {
                            if (val.downloadStatus == '0') {
                                downloaded = true
                            }
                        }
                    })
                    if (downloaded) {
                        console.log('该资源已经下载过了');
                        return
                    }
                    let resType = ''
                    switch (item.fileType) {
                        case '1':
                            item.fileType = 'selfPpt'
                            resType = 'PPT'
                            break;
                        case '2':
                            item.fileType = 'selfPdf'
                            resType = '文档'
                            break;
                        case '3':
                            item.fileType = 'selfWord'
                            resType = '文档'
                            break;
                        case '4':
                            item.fileType = 'selfImg'
                            resType = '图片'
                            break;
                        case '5':
                            item.fileType = 'selfVideo'
                            resType = '视频'
                            break;
                        case '6':
                            item.fileType = 'selfAudio'
                            resType = '音频'
                            break;
                        default:
                            break;
                    }
                    if (item.fileType == _this.$CONST.global.selfPpt   ||
                        item.fileType == _this.$CONST.global.selfPdf   ||
                        item.fileType == _this.$CONST.global.selfWord  ||
                        item.fileType == _this.$CONST.global.selfImg   ||
                        item.fileType == _this.$CONST.global.selfVideo ||
                        item.fileType == _this.$CONST.global.selfAudio){
                        let tempObj = {
                            relationId:item.id,
                            fileId:item.fileId,
                            name: item.displayName,
                            resType: resType,
                            downloadInfo: {
                                FileName: _this.uploadParams.lessonId + '-' + item.displayName,
                                FileType: item.fileType,
                                DBFileName: _this.uploadParams.lessonId + '-' + item.displayName,
                                TaskId: user.id,
                                Url: item.downloadUrl,
                            }
                        }
                       
                        let resName = _this.uploadParams.lessonId + '-' +item.displayName
                        let userResourse  =  SqlLibBook.queryOneResourceByName(SqlLib.getInstance(window.$DBDIR),_this.uploadParams.userId, _this.uploadParams.lessonId,resName)
                        if (userResourse) {
                            console.log('本地数据库有这个资源记录');
                            tempObj.id = userResourse.id
                        }else{
                            let id = UUIDUtil.uuid()
                            tempObj.id = id
                        }
                        tempObj.downloadInfo.Bsr = JSON.stringify(tempObj)
                        downloadParam.DownloadParams.push(tempObj.downloadInfo)
                    }
                })
                //系统云资源库资源
                let sysResource = res.returnValue.resourceIdsVO.resources
                if (sysResource){
                    for( let item in sysResource){
                        let metaInfo = sysResource[item]
                        console.log(item,sysResource[item]);
                        var isRequireSync = true
                        _this.lessonItems.forEach(items=>{
                            if (metaInfo.meta_info.meta_id == items.id && items.downloadStatus == '0') {
                                console.log('已经有这个资源了且已下载');
                                isRequireSync = false
                            }
                        })
                        if (isRequireSync) {
                            downloadParam.DownloadParams.push({
                                Bsr:JSON.stringify(metaInfo),
                                TaskId: metaInfo.meta_info.meta_id,
                                FileType: metaInfo.meta_info.meta_type,
                                FileName: metaInfo.meta_info.meta_type === 'PolyvVideo' ? metaInfo.meta_info.meta_id : metaInfo.meta_info.meta_id + '.zip',
                                Url: metaInfo.meta_info.zip ? _this.$CONST.global.cdnResourcePrefix + metaInfo.meta_info.zip : '',
                                isLessonRes: '1'
                            })
                        } 
                    }
                }
                console.log(downloadParam.DownloadParams);
                // return
            }else{
                _this.$message.warning(res.message)
                return
            }
            if (downloadParam.DownloadParams.length > 0 ) {
                bus.$emit('syncDownload',true)
                setTimeout(() => {
                    _this.startSyncDownload(downloadParam)
                }, 1000);
            }else{
                _this.lessonRedflag = false
                _this.queryDiyResSort()
                this.$message.warning('暂无可同步资源')
            }
        }).catch(error => {
            console.log(error)
            _this.$message.warning('网络异常！')
            return
        })
    },
    //同步资源
    syncResource(){
        if (this.isDiyLesson) {
            this.syncDiyResource()
            return
        }
        //同步资源
        let _this = this
        let lessonId = this.uploadParams.lessonId
        if (DownloadCenter.getInstance().lessonIsDownloading(lessonId)) {
            this.$message.warning('本课程正在下载中')
            return
        }
        let downloadingIds = DownloadCenter.getInstance().getCurrentDownloadingLesson()
        if (downloadingIds.length + 1 > this.$CONST.global.maxDownloadLesson) {
            //超出最大限制之后，不允许下载
            this.$message.warning('同时下载的课程数超过限制，请稍后重试！')
            return
        }
        let sqlLib = SqlLib.getInstance(window.$DBDIR)
        let user = SqlLibUser.queryCurrentUser(sqlLib)
        let tableNames = SqlLibBook.queryChaAndBookNameByLessonId(sqlLib, lessonId)
        let downloadParam = {
            SetDownloadId: lessonId,
            DownloaderInfo: {
              lessonName: this.uploadParams.lessonName,
              bookName: tableNames.bookName,
              publisherName: tableNames.publisherName
            },
            DownloadParams: [],
            ActionStatus: '2' //动作的状态：0 - 下载；1 - 更新；2 - 同步
        }
        //1.先获取所有的PPT
        usermeta.getAllUserLessonFile({
            withFileUrl: '1',
            lessonId: lessonId
        }).then(res => {
            if (res.code == '0') {
            let resData = res.returnValue
            console.log(resData);
            // return
            if (resData instanceof Array) {
                resData.forEach(item => {
                    var downloaded = false
                    _this.lessonItems.forEach(val=>{//判断是否已下载
                        if (item.displayName.indexOf(val.name) !== -1) {
                            if (item.fileType !== '1' && val.downloadInfo.FileType != 'courseware' && val.downloadStatus == '0') {
                                downloaded = true
                            }
                            if (val.downloadInfo.FileType == 'courseware') {
                                console.log('fileMd5',val.fileMd5);
                                if (val.fileMd5 == item.fileMd5) {
                                    downloaded = true
                                }else{
                                    downloaded = false
                                    console.log('可能是修改了系统ppt');
                                }
                            }
                        }
                    })
                    setTimeout(() => {
                        if (downloaded) {
                            console.log('已经下载过了',downloaded);
                            return
                        }
                        let resType = ''
                        switch (item.fileType) {
                            case '1':
                                item.fileType = 'selfPpt'
                                resType = 'PPT'
                                break;
                            case '2':
                                item.fileType = 'selfPdf'
                                resType = '文档'
                                break;
                            case '3':
                                item.fileType = 'selfWord'
                                resType = '文档'
                                break;
                            case '4':
                                item.fileType = 'selfImg'
                                resType = '图片'
                                break;
                            case '5':
                                item.fileType = 'selfVideo'
                                resType = '视频'
                                break;
                            case '6':
                                item.fileType = 'selfAudio'
                                resType = '音频'
                                break;
                            default:
                                break;
                        }
                        if (item.fileType == _this.$CONST.global.selfPpt   ||
                            item.fileType == _this.$CONST.global.selfPdf   ||
                            item.fileType == _this.$CONST.global.selfWord  ||
                            item.fileType == _this.$CONST.global.selfImg   ||
                            item.fileType == _this.$CONST.global.selfVideo ||
                            item.fileType == _this.$CONST.global.selfAudio){
                                if (item.fileType == _this.$CONST.global.selfPpt) {
                                    if (item.fileSource == '1'){
                                        item.displayName = item.displayName.substring(item.displayName.indexOf('-')+1)
                                        console.log('开放平台传过来的',item.displayName);
                                    }else{
                                        let tampNames = item.displayName.split('-')
                                        if (tampNames[0] == _this.uploadParams.lessonId) {
                                            //7.0及之前版本上传的课件
                                            item.displayName = item.displayName.substring(item.displayName.indexOf('-')+1)
                                        }
                                    }
                                }
                                let tempObj = {
                                    relationId:item.id,
                                    fileId:item.fileId,
                                    name: item.displayName,
                                    resType: resType,
                                    downloadInfo: {
                                        FileName: _this.uploadParams.lessonId + '-' + item.displayName,
                                        FileType: item.fileType,
                                        DBFileName: _this.uploadParams.lessonId + '-' + item.displayName,
                                        TaskId: user.id,
                                        Url: item.downloadUrl,
                                    }
                                }
                                let resName = _this.uploadParams.lessonId + '-' +item.displayName
                                let userResourse  =  SqlLibBook.queryOneResourceByName(SqlLib.getInstance(window.$DBDIR),_this.uploadParams.userId, _this.uploadParams.lessonId,resName)
                                if (userResourse) {
                                    console.log('本地数据库有这个资源记录');
                                    tempObj.id = userResourse.id
                                }else{
                                    let id = UUIDUtil.uuid()
                                    tempObj.id = id
                                }
                                tempObj.downloadInfo.Bsr = JSON.stringify(tempObj)
                                downloadParam.DownloadParams.push(tempObj.downloadInfo)
                            }
                    },0);
                })
            }
            usermeta.getUserLessonMeta({
                  isDetail: '1',
                  lessonId: lessonId
                })
                .then(resources => {
                if (resources.code == '0') {
                  if (resources.returnValue.lessonMetaVOS && resources.returnValue.lessonMetaVOS[0]) {
                    let metaInfos = resources.returnValue.lessonMetaVOS[0].resMetaInfoVOS
                    let resultBsr = []
                    metaInfos.forEach(metaInfo => {
                        var isNeedDownload = true
                        _this.lessonItems.forEach(items=>{
                            if (metaInfo.meta_id == items.id &&items.downloadStatus == '0') {
                                console.log('已经有这个资源了且已下载');
                                isNeedDownload = false
                            }
                        })
                        if (isNeedDownload) {
                            downloadParam.DownloadParams.push({
                                TaskId: metaInfo.meta_id,
                                FileType: _this.resTypeToEnName(metaInfo.res_type),
                                FileName: _this.resTypeToEnName(metaInfo.res_type) === 'PolyvVideo' ? metaInfo.meta_id : metaInfo.meta_id + '.zip',
                                Url: metaInfo.zip_url ? _this.$CONST.global.cdnResourcePrefix + metaInfo.zip_url : '',
                                isLessonRes: '1'
                            })
                        }
                    })
                    
                    let isRequireSync = false
                    let lessonResource = SqlLibUser.queryLessonResource(sqlLib, user.id, lessonId)
                    console.log(downloadParam);
                    // return
                    downloadParam.DownloadParams.forEach((downParam, index) => {
                        lessonResource.forEach(res => {
                            if (downParam.TaskId === res.resourceId) {
                                if (res.downloadStatus == '0') {
                                    downloadParam.DownloadParams.splice(index,1)
                                }
                            }
                        })
                    })
                    downloadParam.DownloadParams.forEach(param => {
                        if (param.FileType !== _this.$CONST.global.selfPpt  &&
                            param.FileType !== _this.$CONST.global.selfPdf  &&
                            param.FileType !== _this.$CONST.global.selfWord &&
                            param.FileType !== _this.$CONST.global.selfImg  &&
                            param.FileType !== _this.$CONST.global.selfVideo&&
                            param.FileType !== _this.$CONST.global.selfAudio ) {
                            resultBsr.push({
                                metaId: param.TaskId,
                                metaType: param.FileType
                            })
                        }
                    })
                    console.log('resultBsr',resultBsr);
                    if (downloadParam.DownloadParams.length == 0) {
                        isRequireSync = false
                    }else{
                        isRequireSync = true
                    }
                    console.log('isRequireSync => ' + isRequireSync)
                    if (!isRequireSync) {
                        //不需要同步
                        _this.lessonRedflag = false
                        _this.setUserLessonVer()
                        _this.$message.warning('当前没有可同步的资源')
                    } else {
                        // let options = {
                        //     title: '资源同步中，请稍等',
                        //     time: 30000,
                        //     progress: false,
                        //     full: true,
                        // }
                        // let syncMask = _this.$downloadmask('#home', options)
                        
                        if (resultBsr.length === 0) {
                            bus.$emit('syncDownload',true)
                            setTimeout(() => {
                                _this.startSyncDownload(downloadParam)
                            }, 1000);
                        } else {
                          resource
                            .getResourceInfoByResIds({
                              metaParamDTOS: resultBsr
                            })
                            .then(response => {
                                if (response.code == '0') {
                                    let bsrResources = response.returnValue.resources
                                    downloadParam.DownloadParams.forEach((item, index) => {
                                        if (bsrResources[item.TaskId]) {
                                            item.Bsr = JSON.stringify(bsrResources[item.TaskId])
                                        }
                                    })
                                    bus.$emit('syncDownload',true)
                                    setTimeout(() => {
                                        _this.startSyncDownload(downloadParam)
                                    }, 1000);
                                } else {
                                    _this.$message.warning(response.message)
                                    _this.cancelSyncDownloader()
                                }
                            })
                            .catch(error => {
                                console.log(error)
                                _this.$message.warning('网络异常！')
                                _this.cancelSyncDownloader()
                            })
                            }
                        }
                    }
                }else{
                    if (downloadParam.DownloadParams.length > 0) {//有自上传的资源，没有资源中心的系统资源
                        bus.$emit('syncDownload',true)
                        setTimeout(() => {
                            _this.startSyncDownload(downloadParam)
                        }, 2000);
                        } else {
                            _this.lessonRedflag = false
                            _this.setUserLessonVer()
                            _this.$message.warning(resources.message)
                        }
                    }
                })
                .catch(error => {
                    console.log(error)
                    _this.$message.warning('网络异常！')
                })
            } else {
                _this.$message.warning(res.message)
                return
            }
        })
        .catch(error => {
            console.log(error)
            _this.$message.warning('网络异常！')
            return
        })
    },
    startSyncDownload(downloadParam,loadingService) {
        let _this = this
        // console.log('downloadParam---------------',downloadParam)
        _this.syncObj.downloader = new SetDownloaderLib(
        downloadParam,
        function() {
          //异步下载缩略图
          ThumbDownloader.asyncDownloadThumbs(resource, _this.syncObj.downloader.downloadParames)
          ThumbDownloader.asyncDownloadSubtitles(resource, _this.syncObj.downloader.downloadParames)
          _this.syncObj.downloader.startDownload(
            function() {
              //成功回调
              let maskProgress = new CustomEvent('maskProgress', {
                detail: { progress: 100 }
              })
              window.dispatchEvent(maskProgress)
              if (!_this.isDiyLesson) {
                _this.setUserLessonVer()
              }
              if (loadingService) {
                loadingService.close()
              }
              _this.lessonRedflag = false
              bus.$emit('syncDownload',false)
              _this.$message.success('下载成功')
              if (_this.syncObj.downloader) {
                let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR))
                _this.saveResources(_this.syncObj.downloader, user)
                    if (_this.uploadParams.bookId == _this.uploadParams.userId) {
                        bus.$emit('initDiyLesson', _this.uploadParams.lessonId) 
                    }else{
                        bus.$emit('initLesson', _this.uploadParams.lessonId)
                    }
              }
              _this.cancelSyncDownloader()
            },
            function() {
              //失败回调
              _this.$message.warning('下载失败')
              bus.$emit('syncDownload',false)
              _this.cancelSyncDownloader()
            },
            function(progressCallbackVal) {
                //进度回调
                console.log('progressCallbackVal-------------------',JSON.parse(progressCallbackVal));
                progressCallbackVal = JSON.parse(progressCallbackVal)
                let maskProgress = new CustomEvent('maskProgress', {
                  detail: {
                    progress: parseInt(progressCallbackVal.ReturnValue.Progress)
                  }
                })
                window.dispatchEvent(maskProgress)
            }
          )
        },
        function() {
          _this.$message.warning('初始化失败！')
          bus.$emit('syncDownload',false)
          _this.cancelSyncDownloader()
        }
      )
    },
    //保存资源
    saveResources(setDownloader, user) {
        let _this = this
        let params = setDownloader.downloadParames
        console.log('saveResources', params)
        params.forEach((param, index) => {
            let userUpload = false
            if (param.FileType == _this.$CONST.global.selfPpt   ||
                param.FileType == _this.$CONST.global.selfPdf   ||
                param.FileType == _this.$CONST.global.selfWord  ||
                param.FileType == _this.$CONST.global.selfImg   ||
                param.FileType == _this.$CONST.global.selfVideo ||
                param.FileType == _this.$CONST.global.selfAudio){
                    userUpload = true
                    let selfResource = SqlLibBook.queryOneResourceByName(SqlLib.getInstance(window.$DBDIR), user.id, setDownloader.downloaderId,param.DBFileName)
                    if (selfResource) {
                        console.log('本地数据库有记录-------',selfResource);
                        if (setDownloader.errorDownloadTaskIndexes.length > 0 && setDownloader.errorDownloadTaskIndexes.contains(index)) {
                            selfResource.downloadStatus = '1'
                        } else {
                            selfResource.downloadStatus = '0'
                        }
                        if (selfResource.resourceType == 'selfPpt') {
                            let defaultPpt = SqlLibBook.queryDefaultPpt(SqlLib.getInstance(window.$DBDIR),setDownloader.downloaderId)
                            if(!defaultPpt){
                                console.log('没有默认PPT');
                                selfResource.isDefault = '1'
                            }else{
                                console.log('有默认PPT',defaultPpt);
                            }
                        }
                        SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(selfResource)
                    }else{
                        //换了电脑同步，本地数据库没记录
                        let newuserResource = new UserResource()
                        newuserResource.userId = user.id
                        newuserResource.lessonId = setDownloader.downloaderId
                        newuserResource.resourceClassify = '0'
                        newuserResource.resourceType = param.FileType
                        newuserResource.isDefault = '0'
                        newuserResource.resourceName =  param.DBFileName
                        let bsr = JSON.parse(param.Bsr)
                        newuserResource.id = bsr.id
                        newuserResource.resourceId = bsr.id
                        console.log('bsr----------------------------------',bsr);
                        var tampNames = bsr.name.split('-')
                        var newNames = []
                        tampNames.forEach((item)=>{
                            if (item != _this.uploadParams.lessonId) {
                                newNames.push(item)
                            }
                        })
                        
                        var tName = ''
                        if (newNames.length > 1) {
                            tampNames.forEach((item,index)=>{
                                tName = tName  + item
                                if (index !== tampNames.length-1) { //不是最后一个
                                    tName = tName+'-'
                                } 
                            })
                            bsr.name = tName
                        }else{
                            bsr.name = newNames[0]
                        }
                        console.log('newNames',newNames);
                        newuserResource.resourceDescription = JSON.stringify(bsr)
                        newuserResource.reverse1 = bsr.relationId
                        newuserResource.reverse2 = bsr.fileId
                        newuserResource.reverse3 = '0'
                        newuserResource.sortIndex = 100
                        let defaultPpt = SqlLibBook.queryDefaultPpt(SqlLib.getInstance(window.$DBDIR),setDownloader.downloaderId)
                        if(!defaultPpt){
                            console.log('没有默认PPT');
                            newuserResource.isDefault = bsr.resType == 'PPT' ? '1' : '0'
                        }else{
                            console.log('有默认PPT',defaultPpt);
                        }
                        if (setDownloader.errorDownloadTaskIndexes.length > 0 && setDownloader.errorDownloadTaskIndexes.contains(index)) {
                            // console.log('下载失败');
                            newuserResource.downloadStatus = '1'
                        } else {
                            // console.log('下载成功');
                            newuserResource.downloadStatus = '0'
                        }
                        SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(newuserResource)
                    }
            }
            if (userUpload) {
                return
            }
            console.log('非自上传的个人资源');
            let res = SqlLibBook.queryOneResource(SqlLib.getInstance(window.$DBDIR), user.id, setDownloader.downloaderId,param.TaskId)
            if (res) {
                //数据库有
                if (setDownloader.errorDownloadTaskIndexes.length > 0 && setDownloader.errorDownloadTaskIndexes.contains(index)) {
                    res.downloadStatus = '1'
                } else {
                    res.downloadStatus = '0'
                }
                SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(res)
            }else{
                let userResource = new UserResource()
                userResource.id = UUIDUtil.uuid()
                userResource.userId = user.id
                userResource.lessonId = setDownloader.downloaderId
                userResource.resourceClassify = param.isLessonRes ? param.isLessonRes : '2'
                userResource.resourceType = param.FileType
                userResource.resourceId = param.TaskId
                let Bsr = JSON.parse(param.Bsr)
                userResource.resourceDescription = param.Bsr
                userResource.resourceName = Bsr.meta_info.name
                if (setDownloader.errorDownloadTaskIndexes.length > 0 && setDownloader.errorDownloadTaskIndexes.contains(index)) {
                    userResource.downloadStatus = '1'
                } else {
                    userResource.downloadStatus = '0'
                }
                SqlLibBook.updateOrInsertExtraResource(SqlLib.getInstance(window.$DBDIR), userResource)
            }
        })
    },
    //打开资源
    showResource(lessonItem) {
        console.log('resource win be ready to show ')
        if (this.isEdit) {
          return
        }
        if (lessonItem.downloadStatus === '1' || lessonItem.downloadStatus === '2') {
          return
        }
        const path = require('path')
        const fs = require('fs')
        let _this = this
        switch (lessonItem.downloadInfo.FileType) {
            case 'courseware':
                var respath = path.resolve(window.$DATADIR, 'resc', 'courseware',  lessonItem.downloadInfo.TaskId + '.pptx')
                    if(fs.existsSync(respath)){
                        _this.$client.openNativeFile(respath)
                    }else{
                        _this.$client.openNativeFile(path.resolve(window.$DATADIR, 'resc', 'courseware', lessonItem.downloadInfo.TaskId + '.ppt'))
                    }
                break;
            case 'selfPpt':
                _this.$client.openNativeFile(path.resolve(window.$DATADIR, 'resc', 'user', 'ppt', this.uploadParams.userId, lessonItem.downloadInfo.FileName))
                break;
            case 'selfVideo':
                _this.$client.openNativeFile(path.resolve(window.$DATADIR, 'resc', 'user', 'video', this.uploadParams.userId, lessonItem.downloadInfo.FileName))
                break;
            case 'selfImg':
                _this.$client.openNativeFile(path.resolve(window.$DATADIR, 'resc', 'user', 'img', this.uploadParams.userId, lessonItem.downloadInfo.FileName))
                break;
            case 'selfPdf':
                _this.$client.openNativeFile(path.resolve(window.$DATADIR, 'resc', 'user', 'pdf', this.uploadParams.userId, lessonItem.downloadInfo.FileName))
                break;
            case 'selfWord':
                _this.$client.openNativeFile(path.resolve(window.$DATADIR, 'resc', 'user', 'word', this.uploadParams.userId, lessonItem.downloadInfo.FileName))
                break;
            case 'selfAudio':
                _this.$client.openNativeFile(path.resolve(window.$DATADIR, 'resc', 'user', 'audio', this.uploadParams.userId, lessonItem.downloadInfo.FileName))
                break;
            default:
                let params = {
                  userId: this.uploadParams.userId,
                  lessonId: this.uploadParams.lessonId
                }
                if (lessonItem.downloadInfo.FileType === 'PaperFile') {
                  params.metaId = lessonItem.id
                  params.metaType = 'PaperFile'
                } else {
                    params.res_type = JSON.parse(lessonItem.downloadInfo.Bsr) ? JSON.parse(lessonItem.downloadInfo.Bsr).meta_info.res_type : ''
                    params.metaId = JSON.parse(lessonItem.downloadInfo.Bsr) ? JSON.parse(lessonItem.downloadInfo.Bsr).meta_info.meta_id : ''
                    // console.log(JSON.parse(lessonItem.downloadInfo.Bsr));
                }
                if (lessonItem.downloadInfo.FileType == 'Quiz') {
                    var dRes = JSON.parse(lessonItem.downloadInfo.Bsr)
                    var isNewType = false
                    console.log(dRes);
                    if (dRes.entries) {
                        var entriesArr = dRes.entries
                        entriesArr.forEach(item=>{
                            if (item.quiz_type !== 0 && item.quiz_type !== 1 && item.quiz_type !== 2 && item.quiz_type !== 3) {
                                console.log('有新题型');
                                isNewType = true
                            }
                        })
                    }
                    if (isNewType) {
                        this.$message.warning('请升级版本使用该题型')
                        return
                    }
                }
            this.$electron.ipcRenderer.send('showResourceHideWindow', params)
            this.$electron.ipcRenderer.on('showResourceWindow-reply', function(event, arg) {
                _this.$message.warning(arg)
            })
            //保存用户的点击记录
            let recUserResource = new RecUserResource()
            recUserResource.id = UUIDUtil.uuid()
            recUserResource.lessonId = this.uploadParams.lessonId
            recUserResource.userId = this.uploadParams.userId
            recUserResource.gmtCreate = moment().format('YYYY-MM-DD HH:mm:ss')
            if (lessonItem.downloadInfo.FileType === 'courseware') {
                recUserResource.metaInfoId = lessonItem.downloadInfo.TaskId
                recUserResource.metaType = 'courseware'
            } else if (!['selfPpt', 'selfVideo','selfAudio','selfImg','selfWord','selfPdf'].includes(lessonItem.downloadInfo.FileType)) {
                if (lessonItem.downloadInfo.Bsr) {
                    let bsr = JSON.parse(lessonItem.downloadInfo.Bsr)
                    recUserResource.metaInfoId = bsr.meta_info.id
                    recUserResource.metaType = lessonItem.downloadInfo.FileType
                }
            }
            console.log(params)
            cacheLessonItemMap.set(params.metaId, recUserResource)
                break;
            }
    },
    resTypeToName(resType) {
      resType = this.$CONST.global.resourceSwitch[resType]
      return this.$CONST.global.resourceType[resType]
    },
    resTypeToEnName(resType) {
      return this.$CONST.global.resourceSwitch[resType]
    },
    cancelSyncDownloader() {
        if (this.syncObj.downloader) {
            this.syncObj.downloader.cancelDownload()
            this.syncObj.downloader = null
        }
        if (this.syncObj.loadingService) {
            this.syncObj.loadingService.close()
        }
    },
    isOnline() {
        //在线检查
        console.log('isOnline' + (localStorage.isOffline && localStorage.isOffline === 'false'))
        return localStorage.isOffline && localStorage.isOffline === 'false'
    },
    resumeDownload(value) {
        console.log(value);
        // return
        let _this = this
        let downloadParam = {}
        if (value.downloadInfo.FileType === 'courseware') {
            downloadParam = {
                FileType: 'courseware',
                Url: value.downloadInfo.Url,
                TaskId: value.downloadInfo.TaskId
            }
        } else {
            if (value.downloadInfo.FileType === "PaperFile") {
                downloadParam = {
                    FileType: 'PaperFile',
                    FileName:value.downloadInfo.FileName,
                    Url: value.downloadInfo.Url,
                    TaskId: value.downloadInfo.TaskId
                }
            }else{
                if (value.downloadInfo.FileType == 'selfPpt'   ||
                    value.downloadInfo.FileType == 'selfPdf'   ||
                    value.downloadInfo.FileType == 'selfWord'  ||
                    value.downloadInfo.FileType == 'selfImg'   ||
                    value.downloadInfo.FileType == 'selfVideo' ||
                    value.downloadInfo.FileType == 'selfAudio'){
                    downloadParam = {
                        FileName: value.downloadInfo.FileName,
                        FileType: value.downloadInfo.FileType,
                        DBFileName:value.downloadInfo.FileName,
                        TaskId: _this.uploadParams.userId,
                        Url: value.downloadInfo.Url,
                        isLessonRes: '0'
                    }
                }else{
                    let bsr = value.downloadInfo.Bsr
                    bsr = JSON.parse(bsr)
                    downloadParam = {
                        TaskId: bsr.meta_info.meta_id,
                        FileType: _this.resTypeToEnName(bsr.meta_info.res_type),
                        FileName: _this.resTypeToEnName(bsr.meta_info.res_type) === 'PolyvVideo' ? bsr.meta_info.meta_id : bsr.meta_info.meta_id + '.zip',
                        Url: bsr.meta_info.zip ? _this.$CONST.global.cdnResourcePrefix + bsr.meta_info.zip : '',
                        Bsr: value.downloadInfo.Bsr
                    }
                }
            }   
        }
        
        if (value.downloadInfo.FileType == 'selfPpt'   ||
            value.downloadInfo.FileType == 'selfPdf'   ||
            value.downloadInfo.FileType == 'selfWord'  ||
            value.downloadInfo.FileType == 'selfImg'   ||
            value.downloadInfo.FileType == 'selfVideo' ||
            value.downloadInfo.FileType == 'selfAudio') {
                // console.log(_this.uploadParams.lessonId);
            let tableNames = SqlLibBook.queryChaAndBookNameByLessonId(SqlLib.getInstance(window.$DBDIR), _this.uploadParams.lessonId)
            let Param = {
                SetDownloadId: _this.uploadParams.lessonId,
                DownloaderInfo: {
                    lessonName: _this.uploadParams.lessonName,
                    bookName: tableNames.bookName,
                    publisherName: tableNames.publisherName
                },
                DownloadParams: [],
                ActionStatus: '2' //动作的状态：0 - 下载；1 - 更新；2 - 同步
            }
            Param.DownloadParams.push(downloadParam)
            let loadingService = this.$downloadmask('#lesson', {
                title: '资源下载中，请稍等',
            })
            _this.startSyncDownload(Param,loadingService)
            return
        }
        let loadingService = this.$downloadmask('#lesson', {
            title: '资源下载中，请稍等',
        })
        try {
            //异步下载缩略图
            ThumbDownloader.asyncDownloadThumbs(resource, [downloadParam])
            if (value.downloadInfo.FileType == 'BosVideo') {
                ThumbDownloader.asyncDownloadSubtitles(resource, [downloadParam])
            }
        } catch (e) {}
        try {
            CloudResDownloader.getInstance().downloadLessonResource(
                downloadParam,
                function(progress, speed) {
                    //进度回调
                    let maskProgress = new CustomEvent('maskProgress', {
                        detail: {
                            progress: progress ? progress : 0
                        }
                    })
                    window.dispatchEvent(maskProgress)
                },
                function() {
                    //成功回调
                    let maskProgress = new CustomEvent('maskProgress', {
                      detail: { progress: 100 }
                    })
                    window.dispatchEvent(maskProgress)
                    let sqlLib = SqlLib.getInstance(window.$DBDIR)
                    let user = SqlLibUser.queryCurrentUser(sqlLib)
                    let userResource = SqlLibBook.queryOneResource(sqlLib, user.id, _this.uploadParams.lessonId, downloadParam.TaskId)
                    if (userResource != null) {
                      userResource.downloadStatus = '0'
                      sqlLib.updateOrInsertObjectById(userResource)
                      _this.$message.success('下载成功！')
                    } else {
                      _this.$message.warning('该资源不存在！')
                    }
                    loadingService.close()
                    if (_this.uploadParams.userId == _this.uploadParams.bookId) {
                        console.log('下载自定义课程');
                        bus.$emit('initDiyLesson', _this.uploadParams.lessonId)
                    }else{
                        bus.$emit('initLesson', _this.uploadParams.lessonId)
                    }
                },
                function() {
                  //失败回调
                  _this.$message.warning('下载失败，请检查网络！')
                  loadingService.close()
                }
            )
        } catch (e) {
            console.log('errorrrrrrrrrrrr',e);
        }
        
    },
    
    //工具使用时长
    recordToolTime(param) {
      usermeta
        .recordUseTechTool(param)
        .then(res => {
          console.log(res)
        })
        .catch(err => {
          console.log(err)
        })
    },
    //统计资源的点击次数与播放时长
    recordResTimeIsOnLine(mapItem) {
      const paramData = {
        metaInfoId: mapItem.metaInfoId,
        metaType: mapItem.metaType,
        lessonId: mapItem.lessonId,
        playTime: mapItem.playTime
      }
      usermeta
        .createUserResRecord(paramData)
        .then(response => {
          console.log(response)
        })
        .catch(error => {})
    },
    //保存用户的点击记录
    recordResTimeIsOffLine(mapItem) {
        // console.log('mapItem-----------------------------------',mapItem);
        //保存用户的点击记录
        SqlLib.getInstance(window.$DBDIR).insertObject(mapItem)
    },
    computeThumb(v) {
      // console.log(v);
      if (localStorage.isOffline === 'true') {//离线
        console.log('离线状态');
        const path = require('path')
        return path.resolve(window.$DATADIR, 'resc', v.downloadInfo.FileType, v.downloadInfo.TaskId, 'thumb')
      }
      if (v.downloadStatus == '2') {
        return v.thumb
      }
      if (this.uploadParams.isHomeDialogShow) {
        return v.thumb
      } else {
        const path = require('path')
        return path.resolve(window.$DATADIR, 'resc', v.downloadInfo.FileType, v.downloadInfo.TaskId, 'thumb')
      }
     
     
    },
    computeBref(v) {
      // console.log(v)
      if (v.downloadInfo.FileType === 'PaperFile') return v.intro || '暂无简介'
      if (v.downloadInfo.Bsr) {
        let bsr = v.downloadInfo.Bsr
        bsr = JSON.parse(bsr)
        if (bsr.brief) {
          return bsr.brief
        } else {
          return '暂无简介'
        }
      } else {
        return '暂无简介'
      }
    },
    imgLoadError(e) {
        console.log(e);
        if (!e.target) return
        let reload = e.target.dataset.reload
        if (reload <= 3) {
            setTimeout(() => {
                console.log('图片加载出错');
                // bus.$emit('reloadlesson')
                // var strArr = e.target.src.split('/')
                // var str = strArr[strArr.length-2]
                // this.lessonItems.forEach(item => {
                //     if (item.id === str) {
                //         e.target.src = item.thumb
                //     }
                // });
                // e.target.dataset.reload = parseInt(reload) + 1
            }, 500)
        }
    }
  }
}
</script>

<style lang="scss">
#lesson {
  width: 100%;
  background: #fff;
  // padding-top: 22px;
  display: flex;
  flex-direction: column;
  height: 100%;
  transition: all 0.4s ease-out;
  // padding-left: 40px;
}

.header-nav {
  padding: 20px 0;
}
.lesson-lessons {
  padding-top: 20px;
}
.lesson-handel {
    padding: 0 20px;
    border-radius: 4px 0 0 4px;
    white-space: nowrap;
    flex: 1;
    height: 40px;
    line-height: 40px;
    background: #EBF1F7;
    .lessonRedflag{
        margin-left: 5px;
        margin-bottom: 5px;
        width: 6px;
        height: 6px;
        background-color: rgb(248, 27, 27);
        border-radius: 50%;
    }
    .separator {
        display: inline-block;
        width: 1px;
        height: 14px;
        background-color: rgba(209, 219, 226, 1);
        margin: 0 15px;
    }
  .handel-item {
    &:not(:last-child) {
        // margin-left: 15px;
    }
    img {
      width: 17px;
      height: 17px;
      margin-right: 6px;
    }
    a {
      color: #606266;
    }
    .cloud-btn {
      color: #606266;
    }
  }
}
.lesson-res-con {
    margin-top: 10px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  --width: 0;
}
.lesson-res::-webkit-scrollbar {
  display: none;
}
.lesson::-webkit-scrollbar {
  display: none;
}
.default-ppt {
    position: absolute;
    top: 0px;
    right:0px;
    width: 64px;
    height: 24px;
    line-height: 24px;
    background: #f7b500;
    border-radius: 0px 4px 0px 4px;
    color: #fff;
    padding: 0 9px;
    font-size: 12px;
    z-index: 2;
}
.resLabel{
    position: absolute;
    top: 0px;
    right: 0px;
    border-radius: 0px 4px 0px 4px;
    width: 64px;
    height: 24px;
    line-height: 24px;  
    background: #000000;
    opacity: 0.6;
    white-space: nowrap;
    color: #fff;
    padding: 0 9px;
    font-size: 12px;
    z-index: 9;
}
.add-res {
  line-height: calc(2em - 4px);
  height: calc(2em - 4px);
}
.edit_wrapper{
    position: absolute;
    bottom:45px;
    display: flex;
    width: 100%;
    justify-content: space-around;
    .singleEdit{
        cursor: pointer;
        width: 86px;
        height: 36px;
        background-color: #0091ff;
        color: #fff;
        border-radius: 20px;
        line-height: 36px;
        text-align: center;
        z-index: 99;
    }
    .alone{
        position: absolute;
        right: 15px;
        bottom:0px;
    }
}
.lesson-res {
  width: calc(100% - var(--width));

  padding-bottom: 10px;
//   display: grid;
//   grid-template-columns: repeat(auto-fill, 347px);
//   grid-template-rows: repeat(auto-fill, 240px);
//   gap: 29px;
  overflow-x: hidden;
  overflow-y: auto;
  align-content: start;
  height: 100%;
  &-lessons {
    height: 100%;
  }
  .resItem{
    width: 100%;
    display: grid;
    grid-template-columns: repeat(auto-fill, 347px);
    grid-template-rows: repeat(auto-fill, 240px);
    gap: 29px;
    overflow-x: hidden;
    overflow-y: auto;
    // align-content: start;
    // height: 100%;
    // display:flex;
    // flex-wrap: wrap;
  }
  .ghost{
    opacity: 0!important;
  }
  .res-name {
    overflow: hidden;
    max-width: 50%;
    min-width: 30%;
    position: relative;
    height: 2em;
    line-height: 2em;
    font-size: 18px;
  }
  .txt {
    max-height: 4em;
    position: relative;
  }
  .title {
    white-space: nowrap;
    text-overflow: ellipsis;
    // background-color: #deedfa;
    background: #EEEEEE;
    overflow: hidden;
    position: relative;
    top: -4em;
  }
  .title:hover {
    display: inline-block;
    animation: move 3s 0.3s linear infinite;
  }
  .title::after {
    content: attr(data-name);
    padding: 0 2em;
  }

  @keyframes move {
    to {
      transform: translate3d(-50%, 0, 0);
    }
  }
  .l-r-items {
    display: flex;
    flex-direction: column;
    position: relative;
    // max-height: 380px;
    // width: 367px;
    // background: rgba(255, 255, 255, 1);
    border-radius: 4px;
    .lesson-message {
      width: 100%;
      display: flex;
      background: #EEEEEE;
      justify-content: flex-start;
      align-items: center;
      padding: 0 10px 0 20px;
      border-radius: 0 0 4px 4px;
      position: relative;
      height: 45px;
      .separator {
        width: 2px;
        height: 14px;
        background-color: #DADADA;
        margin: 0 10px;
      }
      .res-type {
        white-space: nowrap;
        color: #606266;
      }
      .setDefault{
        font-size: 14px;
        color: #606266;
        padding: 3px 5px;
        margin-left: 10px;
        text-align: center;
        white-space: nowrap;
        border: 1px solid #606266;
        border-radius: 32px;
        cursor: pointer;
      }
    }
    .lesson-item-btn {
      height: 32px;
      line-height: 32px;
      text-align: center;
    //   border: 1px solid #0091ff;
      position: absolute;
      bottom: 7px;
      right: 8px;
      border: none;
      background: none;
      cursor: pointer;
      img {
        width: 12px;
        height: 8px;
      }
    }
    .lesson-edit-btn {
      height: 32px;
      line-height: 32px;
      text-align: center;
      color: #0091ff;
      background: none;
      border: none;
      cursor: pointer;
      // position: relative;
      img {
        width: 12px;
        height: 8px;
        position: absolute;
        right: 8px;
        top: 3px;
        bottom: 0;
        margin: auto 0;
        z-index: 3;
      }
    }
    .bottom-type {
      width: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      padding: 10px 0;
    }
    .thumbnail-container {
      position: relative;
      overflow: hidden;
      width: 100%;
      height: 195px;
      &:hover {
        .resource-description {
          display: block;
        }
      }
      .resource-description {
        position: absolute;
        z-index: 19;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.7);
        color: #fff;
        padding: 0 20px;
        padding-top: 40px;
        display: none;
      }
      .downloadFail {
        position: absolute;
        z-index: 10;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255, 255, 255, 0.7);
        .download-again {
          display: flex;
          justify-content: center;
          align-items: center;
          color: #606266;
          flex-direction: column;
          z-index: 20 !important;
          img {
            width: 48px;
            height: 48px;
            margin-bottom: 10px;
          }
        }
      }
      .description-content {
        font-size: 14px;
        line-height: 24px;
        margin-top: 16px;
      }
      img {
        width: 100%;
        height: 100%;
        vertical-align: top;
        border-top-left-radius: 4px;
        border-top-right-radius: 4px;
      }
    }
    .dropdown-menu-container {
      position: absolute;
      bottom: 7px;
      right: 8px;
      line-height: 0;
    }
    .el-dropdown-link {
      img {
        width: 26px;
        height: 6px;
      }
    }
    .category {
      position: absolute;
      top: 0px;
      right: 8px;
      img {
        height: 42px;
        width: 112px;
      }
    }
    .download-fail-tips {
      position: absolute;
      right: 15px;
      bottom: 45px;
    }
    .fail-logo {
      width: 20px;
      height: 20px;
      border: 2px solid rgba(246, 108, 108, 1);
      border-radius: 50%;
      line-height: 20px;
      text-align: center;
      margin-right: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
    }

    .cloud-btn {
      outline: none;
      text-align: center;
      width: 64px;
      line-height: 28px;
      height: 28px;
      background: rgba(72, 147, 255, 0.05);
      border: 1px solid rgba(72, 147, 255, 1);
      border-radius: 14px;
      font-size: 14px;
      color: #4893ff;
      cursor: pointer;
    }
    @media screen and (max-width: 1439px) {
      .download-fail-tips {
        bottom: 30px;
      }
      .fail-logo {
        width: 18px;
        height: 18px;
        margin-right: 3px;
      }
    }
  }
  @media screen and(max-height:800px ) {
    height: 26.6vh;
  }
  .defaultppt-logo {
    position: absolute;
    width: 79px;
    height: 27px;
    z-index: 100;
    top: -3px;
    left: -2px;
    border-top-left-radius: 16px;
  }
}
</style>
